<template>
  <div class="feedback-container">
    <div class="feedback-content">
      <!-- 查询条件 -->
      <t-form ref="form" :data="queryParams" label-width="80px" layout="inline" class="search-form" colon>
        <t-row style="width: 100%">
          <t-col :span="3">
            <t-form-item label="状态">
              <t-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                clearable
                style="width: 158px"
              >
                <t-option
                  v-for="(label, value) in FeedbackStatusLabels"
                  :key="value"
                  :value="value"
                  :label="label"
                >
                  {{ label }}
                </t-option>
              </t-select>
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item>
              <t-space>
                <t-button theme="primary" @click="handleSearch"> 查询 </t-button>
              </t-space>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-row justify="end">
              <t-button theme="primary" variant="base" :loading="exportLoading" @click="handleExport">
                <template #icon>
                  <t-icon name="download" />
                </template>
                导出
              </t-button>
            </t-row>
          </t-col>
        </t-row>
      </t-form>

      <!-- 反馈列表表格 -->
      <div class="feedback-table">
        <t-table
          row-key="id"
          bordered
          height="calc(100vh - 55px - 28px - 28px - 16px - 64px - 70px)"
          :data="feedbackList"
          :columns="columns"
          :loading="loading"
          :pagination="pagination"
          @page-change="onPageChange"
        >
          <!-- 状态列 -->
          <template #status="{ row }">
            <t-tag :theme="getStatusTheme(row.status)">
              {{ FeedbackStatusLabels[row.status] || row.status }}
            </t-tag>
          </template>

          <!-- 操作列 -->
          <template #op="{ row }">
            <div style="display: flex;">
              <t-button theme="success" variant="text" @click="handleEdit(row)">
                修改状态
              </t-button>
              <t-button theme="danger" variant="text" @click="handleDelete(row)"> 删除 </t-button>
            </div>
          </template>
        </t-table>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getFeedbackPage,
  deleteFeedback,
  updateFeedbackStatus,
  FeedbackStatus,
  FeedbackStatusLabels,
} from '@/api/feedback';
import { exportFeedbackData } from '@/api/data';
import { DialogPlugin as TDialog, MessagePlugin } from 'tdesign-vue';

export default {
  name: 'Feedback',
  data() {
    return {
      loading: false,
      feedbackList: [],
      FeedbackStatus,
      FeedbackStatusLabels,
      selectedStatus: '', // 选中的状态值，每次弹框打开时清空

      // 查询参数
      queryParams: {
        status: null,
      },

      // 表格列配置
      columns: [
        { colKey: 'content', title: '内容', ellipsis: true },
        { colKey: 'status', title: '状态', width: 100, align: 'center' },
        { colKey: 'createdAt', title: '创建时间', width: 180 },
        { colKey: 'op', title: '操作', width: 180, fixed: 'right' },
      ],

      // 分页配置
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showJumper: true,
        showPageSize: true,
        pageSizeOptions: [10, 20, 50, 100],
      },

      exportLoading: false,
    };
  },

  mounted() {
    this.loadFeedbackList();
  },

  methods: {
    // 加载反馈列表
    async loadFeedbackList() {
      try {
        this.loading = true;
        const params = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.queryParams,
        };

				// 如果status没有值则删除
				if (!params?.status) {
					delete params.status;
				}

        const response = await getFeedbackPage(params);

        // 参考 recommend 的数据处理方式
        // axios返回的完整response对象结构: { data: { data: { data: [...], total: 427, page: 1, pageSize: 10 } } }
        if (response && response.data && response.data.data) {
          this.feedbackList = Array.isArray(response.data.data.data) ? response.data.data.data : [];
          this.pagination.total = Number(response.data.data.total) || 0;
          // 可选：同步其他分页信息
          this.pagination.current = Number(response.data.data.page) || this.pagination.current;
          this.pagination.pageSize =
            Number(response.data.data.pageSize) || this.pagination.pageSize;
        } else {
          this.feedbackList = [];
          this.pagination.total = 0;
        }
      } catch (error) {
        console.error('加载反馈列表失败:', error);
        MessagePlugin.error('加载反馈列表失败');
        this.feedbackList = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1;
      this.loadFeedbackList();
    },

    // 分页变化
    onPageChange({ current, pageSize }) {
      this.pagination.current = current;

      if (pageSize !== this.pagination.pageSize) {
        this.pagination.current = 1;
      }

      this.pagination.pageSize = pageSize;

      this.loadFeedbackList();
    },

    // 查看反馈
    handleView(row) {
      // TODO: 实现查看功能
      MessagePlugin.info(`查看反馈: ${row.content}`);
    },

    // 编辑反馈状态
    async handleEdit(row) {
      // 每次打开弹框时清空选中状态
      this.selectedStatus = '';

      const statusOptions = [
        { label: '新建', value: FeedbackStatus.NEW },
        { label: '处理中', value: FeedbackStatus.PROCESSING },
        { label: '已完成', value: FeedbackStatus.COMPLETED },
        { label: '已拒绝', value: FeedbackStatus.REJECTED },
      ];

      const currentStatus = row.status;

      // 创建状态选择对话框
      const dialogInstance = TDialog.confirm({
        header: '修改反馈状态',
        body: () => {
          return this.$createElement(
            'div',
            {
              style: { padding: '16px 0' },
            },
            [
              this.$createElement(
                'div',
                {
                  style: { marginBottom: '16px' },
                },
                [
                  this.$createElement(
                    'span',
                    {
                      style: {
                        display: 'inline-block',
                        minWidth: '80px',
                        color: '#666',
                      },
                    },
                    '当前状态：'
                  ),
                  this.$createElement(
                    't-tag',
                    {
                      props: {
                        theme: this.getStatusTheme(currentStatus),
                      },
                    },
                    FeedbackStatusLabels[currentStatus]
                  ),
                ]
              ),
              this.$createElement('div', [
                this.$createElement(
                  'label',
                  {
                    style: {
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontWeight: '500',
                    },
                  },
                  '选择新状态：'
                ),
                this.$createElement(
                  't-select',
                  {
                    props: {
                      value: this.selectedStatus,
                      placeholder: '请选择状态',
                      style: { width: '100%' },
                    },
                    on: {
                      change: (value) => {
                        this.selectedStatus = value;
                      },
                    },
                  },
                  statusOptions.map((option) =>
                    this.$createElement(
                      't-option',
                      {
                        key: option.value,
                        props: {
                          value: option.value,
                          label: option.label,
                        },
                      },
                      option.label
                    )
                  )
                ),
              ]),
            ]
          );
        },
        confirmBtn: '确定修改',
        cancelBtn: '取消',
        onConfirm: async () => {
          if (this.selectedStatus === currentStatus) {
            MessagePlugin.warning('请选择不同的状态');
            return false; // 阻止对话框关闭
          }

          try {
            // 显示加载状态
            dialogInstance.update({
              confirmBtn: {
                content: '修改中...',
                loading: true,
              },
            });

            const res = await updateFeedbackStatus(row.id, { status: this.selectedStatus });

            // 判断是否修改成功
            if (res && res.data && res.data.code === 200) {
              MessagePlugin.success('状态修改成功');
              this.loadFeedbackList();
							dialogInstance.hide();
            } else {
              // 修改失败
              const errorMsg = res?.data?.message || '修改失败，请重试';
              MessagePlugin.error(errorMsg);

              // 恢复按钮状态
              dialogInstance.update({
                confirmBtn: {
                  content: '确定修改',
                  loading: false,
                },
              });
              return false; // 阻止对话框关闭
            }
          } catch (error) {
            console.error('修改反馈状态失败:', error);
            MessagePlugin.error('修改反馈状态失败');

            // 恢复按钮状态
            dialogInstance.update({
              confirmBtn: {
                content: '确定修改',
                loading: false,
              },
            });
            return false; // 阻止对话框关闭
          }
        },
      });
    },

    // 删除反馈 - 参考 recommend 的实现
    async handleDelete(row) {
      // 基本验证
      if (!row || !row.id) {
        MessagePlugin.error('无效的数据');
        return;
      }

      const confirmMessage = `确定要删除反馈"${row.content?.substring(0, 20)}${
        row.content?.length > 20 ? '...' : ''
      }"吗？`;
      const warningMessage = '删除后不可恢复。';

      try {
        // 使用TDesign推荐的确认对话框
        const confirmDialog = await new Promise((resolve) => {
          const instance = TDialog.confirm({
            header: '确认删除',
            body: () => {
              return this.$createElement(
                'div',
                {
                  style: {
                    lineHeight: '1.6',
                  },
                },
                [
                  this.$createElement(
                    'p',
                    {
                      style: {
                        margin: '0 0 8px 0',
                        color: '#333',
                      },
                    },
                    confirmMessage
                  ),
                  this.$createElement(
                    'p',
                    {
                      style: {
                        margin: '0',
                        color: '#ff4d4f',
                        fontWeight: '500',
                      },
                    },
                    warningMessage
                  ),
                ]
              );
            },
            confirmBtn: {
              content: '确定删除',
              theme: 'danger',
              loading: false,
            },
            cancelBtn: '取消',
            onConfirm: () => {
              resolve(instance);
            },
            onCancel: () => {
              resolve(null);
            },
          });
        });

        // 用户取消删除
        if (!confirmDialog) {
          return;
        }

        // 显示删除按钮加载状态
        confirmDialog.update({
          confirmBtn: {
            content: '删除中...',
            theme: 'danger',
            loading: true,
          },
        });

        // 调用删除API
        const res = await deleteFeedback(row.id);

        confirmDialog.hide();
        MessagePlugin.success('删除成功');
        // 重新加载反馈列表
        await this.loadFeedbackList();
      } catch (error) {
        console.error('删除反馈失败:', error);

        // 根据错误类型显示不同的错误信息
        let errorMessage = '删除失败';
        if (error.message) {
          errorMessage = error.message;
        } else if (error.response?.data?.message) {
          errorMessage = error.response.data.message;
        } else if (error.response?.status === 403) {
          errorMessage = '没有权限删除此内容';
        } else if (error.response?.status === 409) {
          errorMessage = '该内容正在被使用，无法删除';
        } else if (error.code === 'NETWORK_ERROR') {
          errorMessage = '网络连接失败，请检查网络后重试';
        }

        MessagePlugin.error(errorMessage);

        // 如果对话框还存在，隐藏它
        if (confirmDialog && typeof confirmDialog.hide === 'function') {
          confirmDialog.hide();
        }
      }
    },

    // 获取状态主题色
    getStatusTheme(status) {
      const themeMap = {
        [FeedbackStatus.NEW]: 'primary',
        [FeedbackStatus.PROCESSING]: 'warning',
        [FeedbackStatus.COMPLETED]: 'success',
        [FeedbackStatus.REJECTED]: 'danger',
      };
      return themeMap[status] || 'default';
    },

    // 导出反馈数据
    async handleExport() {
      try {
        this.exportLoading = true;

        const response = await exportFeedbackData();

        // 创建blob URL并触发下载
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });

        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;

        // 生成文件名，包含时间戳
        const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '');
        link.download = `反馈数据_${timestamp}.xlsx`;

        // 触发下载
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        MessagePlugin.success('导出成功');
      } catch (error) {
        console.error('导出反馈数据失败:', error);

        // 根据错误类型显示不同的错误信息
        let errorMessage = '导出失败';
        if (error.response?.data?.message) {
          errorMessage = error.response.data.message;
        } else if (error.response?.status === 403) {
          errorMessage = '没有权限导出数据';
        } else if (error.code === 'NETWORK_ERROR') {
          errorMessage = '网络连接失败，请检查网络后重试';
        } else if (error.code === 'ECONNABORTED') {
          errorMessage = '导出超时，请稍后重试';
        }

        MessagePlugin.error(errorMessage);
      } finally {
        this.exportLoading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.feedback-container {
  padding: 16px;
  background: #fff;
}

.feedback-content {
  .search-form {
    background: #f8f9fa;
    padding: 16px;
    border-radius: 6px;
    margin-bottom: 16px;
  }

  .feedback-table {
    background: #fff;
    border-radius: 6px;
  }
}
</style>
